package com.king.base.rest.dept;
import com.king.base.aop.DataScope;
import com.king.base.aop.Log;
import com.king.base.domain.dept.Dept;
import com.king.base.exception.BadRequestException;
import com.king.base.service.dept.DeptService;
import com.king.base.auth.utils.EntityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

/**
 * @author Spur
 * @date 2019/6/24
 */
@RestController
@RequestMapping(value = "api/core/dept")
@Api(value = "dept",description = "部门管理Controller")
public class DeptController {
    @Autowired
    private DeptService deptService;
    @GetMapping(value = "/getById/{id}")
    @ApiOperation(value = "根据ID获取一个部门实例")
    public ResponseEntity getById(@PathVariable String id){
        return new ResponseEntity(deptService.getById(id),HttpStatus.OK);
    }
    @GetMapping(value = "/list")
    @ApiOperation(value = "部门树形列表")
    @Log(description = "部门查询")
    @DataScope(scopeSql = "")
    public ResponseEntity list(Dept dept){
        List<Dept> deptList=deptService.selectDeptList(dept);
        return new ResponseEntity(deptService.buildDeptTree(deptList),HttpStatus.OK);
    }
    @GetMapping(value = "/tree")
    @ApiOperation(value = "部门下拉选择器")
    public ResponseEntity tree(Dept dept){
        List<Dept> deptList=deptService.selectDeptList(dept);
        return new ResponseEntity(deptService.buildDeptTreeSelect(deptList),HttpStatus.OK);
    }
    @PostMapping(value = "/create")
    @ApiOperation(value = "部门创建")
    @Log(description = "部门创建")
    public ResponseEntity create(@RequestBody Dept dept){
        if(deptService.checkDeptNameUnique(dept)){
            throw new BadRequestException("部门"+dept.getDeptName()+"已经存在");
        }
        return new ResponseEntity(deptService.saveOrUpdate(dept),HttpStatus.CREATED);
    }
    @PutMapping(value = "/update")
    @ApiOperation(value = "部门修改")
    @Log(description = "部门修改")
    public ResponseEntity update(@RequestBody Dept dept){
        if(deptService.checkDeptNameUnique(dept)){
            throw new BadRequestException("部门"+dept.getDeptName()+"已经存在");
        }
        return new ResponseEntity(deptService.saveOrUpdate(dept),HttpStatus.OK);
    }
    @DeleteMapping(value = "/delete/{deptId}")
    @ApiOperation(value = "部门删除")
    @Log(description = "部门删除")
    public ResponseEntity delete(@PathVariable String deptId){
        if(deptService.hasChildByDeptId(deptId)){
            throw new BadRequestException("请先删除子部门");
        }
        if(deptService.checkDeptExistUser(deptId)){
            throw new BadRequestException("部门存在用户,不允许删除");
        }
        deptService.removeById(deptId);
        return new ResponseEntity(HttpStatus.OK);
    }
}
